package com.atxiaodei.kabudarpc.client;

import com.atxiaodei.kabudarpc.bean.RpcRequest;

import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.Socket;

/**
 * @ClassName RpcNetTransport
 * @Deacription TODO
 * @Author 卡布达
 * @Date 2021/10/31 16:33
 * @Version 1.0
 **/
public class RpcNetTransport {

    private String host;

    private int port;

    public RpcNetTransport(String host,int port){
        this.host=host;
        this.port=port;
    }
    // 借助socket，客户端向服务端发送接口信息
    public Object send(RpcRequest rpcRequest){
        // 向服务端输出
        ObjectOutputStream objectOutputStream=null;
        // 获取服务端响应信息
        ObjectInputStream objectInputStream=null;

        Socket socket=null;

        try {
            socket=new Socket(host,port);
            objectOutputStream=new ObjectOutputStream(socket.getOutputStream());
            objectOutputStream.writeObject(rpcRequest);
            objectOutputStream.flush();

            objectInputStream=new ObjectInputStream(socket.getInputStream());
            Object object = objectInputStream.readObject();
            return object;
        } catch (IOException | ClassNotFoundException e) {
            e.printStackTrace();
        }
        return null;
    }
}
